package cn.acyou.actions.convertJson;

import cn.acyou.utils.CommonUtil;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.openapi.wm.ex.ToolWindowEx;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * MyTool 窗口
 * @author youfang
 * @version [1.0.0, 2021/3/24]
 **/
public class MyToolWindowFactory implements ToolWindowFactory {
    public static MyTools myToolWindow = null;
    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        myToolWindow = new MyTools(toolWindow);
        ContentFactory contentFactory = ContentFactory.SERVICE.getInstance();
        Content content = contentFactory.createContent(myToolWindow.getContent(), "", false);
        toolWindow.getContentManager().addContent(content);
        if (toolWindow instanceof ToolWindowEx) {
            ToolWindowEx toolWindowEx = (ToolWindowEx) toolWindow;
            toolWindowEx.setTitleActions(new MyToolAction(AllIcons.Actions.Refresh));
        }
    }

    static class MyToolAction extends AnAction {
        public MyToolAction(Icon refresh) {
            super(refresh);
        }

        @Override
        public void actionPerformed(@NotNull AnActionEvent e) {
            Project project = e.getProject();
            if (project == null) {
                return;
            }
            Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
            //DataContext dataContext = ((EditorImpl) selectedTextEditor).getDataContext();
            PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
            if (psiFile instanceof PsiJavaFile){
                PsiJavaFile javaFile = (PsiJavaFile) psiFile;
                PsiClass[] classes = javaFile.getClasses();
                PsiClassType classType = PsiTypesUtil.getClassType(classes[0]);
                CommonUtil.convertToJson(project, classType);
            }
        }
    }

    public static void setContent(String content){
        myToolWindow.setContent(content);
    }

}